//
//  NSString+DFDate.m
//  FrameWork
//
//  Created by 王*风 on ****/5/9.
//

#import "NSString+DFDate.h"

@implementation NSString (DFDate)

/** 根据时间格式获取当前时间*/
+(NSString *)df_getCurrentDateDateFormat:(NSString*)dateFormat
{
    NSDate *timer = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setDateStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:dateFormat];
    //设置时区
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/BeiJing"];
    [formatter setTimeZone:timeZone];
    NSString *timerStr = [formatter stringFromDate:timer];
    return timerStr;
}
/** 获取当前时间戳(毫秒)*/
+(NSString*)df_getCurrentTimestamp
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;

       [formatter setDateStyle:NSDateFormatterMediumStyle];

       [formatter setTimeStyle:NSDateFormatterShortStyle];

       [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

       //设置时区,这个对于时间的处理有时很重要

       NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

       [formatter setTimeZone:timeZone];

       NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式

       NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];

       return timeSp;
}

/** 时间戳转化为自定义的时间*/
+(NSString*)df_timeStampBecomeDate:(NSString*)timestamp withFormatterStyle:(NSString*)formatterStr
{

    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    [formatter setDateStyle:NSDateFormatterMediumStyle];

    [formatter setTimeStyle:NSDateFormatterShortStyle];

    [formatter setDateFormat:formatterStr]; // （@"yyyy-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];

    [formatter setTimeZone:timeZone];

    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue]/1000.0];

    

    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];


    return confromTimespStr;
    
    
    
}

/** 将自定义的时间转化为时间戳*/
+(NSInteger)df_dateBecomeTimeStamp:(NSString *)formatTime andFormatter:(NSString *)format
{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:format]; //(@"yyyy-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];

    NSDate* date = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
    
    //时间转时间戳的方法:
    
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];

    return timeSp;
    
}

/** 传入两个时间和格式，获取时间差，单位秒 */
+(NSInteger)df_duringTimeWithBeginTime:(NSString *)beginTime endTime:(NSString *)endTime andFormatter:(NSString *)format {
    NSInteger beginTimeStamp = [NSString df_dateBecomeTimeStamp:beginTime andFormatter:format];
    NSInteger endTimeStamp = [NSString df_dateBecomeTimeStamp:endTime andFormatter:format];
    NSInteger duringStamp = endTimeStamp - beginTimeStamp;
    return duringStamp;
}

/** 传入今天的时间，返回明天的时间*/
+(NSString *)df_getTodayToTomorrowDay:(NSDate *)aDate
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]+1)];
    
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:@"yyyy/MM/dd"];
    return [dateday stringFromDate:beginningOfWeek];
}

/** 获取当前周的周一和周日的时间*/
+(NSString *)df_getMondayAndSunday
{
    NSDate *nowDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitDay fromDate:nowDate];
    // 获取今天是周几
    NSInteger weekDay = [comp weekday];
    // 获取几天是几号
    NSInteger day = [comp day];
    
    // 计算当前日期和本周的星期一和星期天相差天数
    long firstDiff,lastDiff;
    //    weekDay = 1;
    if (weekDay == 1)
    {
        firstDiff = -6;
        lastDiff = 0;
    }
    else
    {
        firstDiff = [calendar firstWeekday] - weekDay + 1;
        lastDiff = 8 - weekDay;
    }
    NSLog(@"firstDiff: %ld   lastDiff: %ld",firstDiff,lastDiff);
    
    // 在当前日期(去掉时分秒)基础上加上差的天数
    NSDateComponents *firstDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:nowDate];
    [firstDayComp setDay:day + firstDiff];
    NSDate *firstDayOfWeek = [calendar dateFromComponents:firstDayComp];
    
    NSDateComponents *lastDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay   fromDate:nowDate];
    [lastDayComp setDay:day + lastDiff];
    NSDate *lastDayOfWeek = [calendar dateFromComponents:lastDayComp];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd"];
    NSString *firstDay = [formatter stringFromDate:firstDayOfWeek];//周一时间
    NSString *lastDay = [formatter stringFromDate:lastDayOfWeek];//周日时间
   
    
    NSString *dateStr = [NSString stringWithFormat:@"%@-%@",firstDay,lastDay];//同时返回周一和周日的时间
 
    return dateStr;
    
}

/** 获取当前月的上一个月份*/
+ (NSString*)df_getBeforeMonthTime
{
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM"];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
    //    [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期，month day 类推
    [lastMonthComps setMonth:-1];
    NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
    NSString *dateStr = [formatter stringFromDate:newdate];
    NSLog(@"date str = %@", dateStr);
    
    return dateStr;
}

/** 将NSString类型转化为NSdate类型*/
+(NSDate*)df_nsstringChangeDateFormat:(NSString*)dateFormat datestring:(NSString*)datestring
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    NSDate *date = [dateFormatter dateFromString:datestring];
    return date;
}

/** 根据年份来获取具体的生肖年份(阴历)*/
+(NSString *)df_getChineseYearWithDate:(NSDate *)date
{
    NSArray *chineseYears = [NSArray arrayWithObjects:
                             @"甲子", @"乙丑", @"丙寅", @"丁卯",  @"戊辰",  @"己巳",  @"庚午",  @"辛未",  @"壬申",  @"癸酉",
                             @"甲戌",   @"乙亥",  @"丙子",  @"丁丑", @"戊寅",   @"己卯",  @"庚辰",  @"辛巳",  @"壬午",  @"癸未",
                             @"甲申",   @"乙酉",  @"丙戌",  @"丁亥",  @"戊子",  @"己丑",  @"庚寅",  @"辛卯",  @"壬辰",  @"癸巳",
                             @"甲午",   @"乙未",  @"丙申",  @"丁酉",  @"戊戌",  @"己亥",  @"庚子",  @"辛丑",  @"壬寅",  @"癸卯",
                             @"甲辰",   @"乙巳",  @"丙午",  @"丁未",  @"戊申",  @"己酉",  @"庚戌",  @"辛亥",  @"壬子",  @"癸丑",
                             @"甲寅",   @"乙卯",  @"丙辰",  @"丁巳",  @"戊午",  @"己未",  @"庚申",  @"辛酉",  @"壬戌",  @"癸亥", nil];
    
    NSCalendar *localeCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
    
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    
    NSDateComponents *localeComp = [localeCalendar components:unitFlags fromDate:date];
    
    
    NSString *y_str = [chineseYears objectAtIndex:localeComp.year - 1];
    
    NSString *Cz_str = nil;
    if ([y_str hasSuffix:@"子"]) {
        Cz_str = @"鼠";
    }else if ([y_str hasSuffix:@"丑"]){
        Cz_str = @"牛";
    }else if ([y_str hasSuffix:@"寅"]){
        Cz_str = @"虎";
    }else if ([y_str hasSuffix:@"卯"]){
        Cz_str = @"兔";
    }else if ([y_str hasSuffix:@"辰"]){
        Cz_str = @"龙";
    }else if ([y_str hasSuffix:@"巳"]){
        Cz_str = @"蛇";
    }else if ([y_str hasSuffix:@"午"]){
        Cz_str = @"马";
    }else if ([y_str hasSuffix:@"未"]){
        Cz_str = @"羊";
    }else if ([y_str hasSuffix:@"申"]){
        Cz_str = @"猴";
    }else if ([y_str hasSuffix:@"酉"]){
        Cz_str = @"鸡";
    }else if ([y_str hasSuffix:@"戌"]){
        Cz_str = @"狗";
    }else if ([y_str hasSuffix:@"亥"]){
        Cz_str = @"猪";
    }
    
    return  [NSString stringWithFormat:@"%@%@",y_str,Cz_str];
}

/** 获取农历(阴历)的月,日*/
+(NSString *)df_getChineseCalendarWithDate:(NSDate *)date
{
    NSArray *chineseMonths=[NSArray arrayWithObjects:
                            @"正月", @"二月", @"三月", @"四月", @"五月", @"六月", @"七月", @"八月",
                            @"九月", @"十月", @"冬月", @"腊月", nil];
    
    NSArray *chineseDays=[NSArray arrayWithObjects:
                          @"初一", @"初二", @"初三", @"初四", @"初五", @"初六", @"初七", @"初八", @"初九", @"初十",
                          @"十一", @"十二", @"十三", @"十四", @"十五", @"十六", @"十七", @"十八", @"十九", @"二十",
                          @"廿一", @"廿二", @"廿三", @"廿四", @"廿五", @"廿六", @"廿七", @"廿八", @"廿九", @"三十",  nil];
    
    
    NSCalendar *localeCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
    
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    
    NSDateComponents *localeComp = [localeCalendar components:unitFlags fromDate:date];
    
    NSString *m_str = [chineseMonths objectAtIndex:localeComp.month-1];
    
    NSString *d_str = [chineseDays objectAtIndex:localeComp.day-1];
    
    NSString *chineseCal_str =[NSString stringWithFormat: @"%@%@",m_str,d_str];
    
    return chineseCal_str;
}

/** 获取今天是周几*/
+(NSString *)df_getCurrentWeekDate:(NSDate *)date
{
    //只适用于iOS8
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 通过已定义的日历对象，获取某个时间点的NSDateComponents表示，并设置需要表示哪些信息（NSYearCalendarUnit, NSMonthCalendarUnit, NSDayCalendarUnit等）
    
    NSDateComponents *dateComponents = [greCalendar components:NSCalendarUnitWeekday fromDate:date];
    NSString *str = [NSString stringWithFormat:@"%li",(long)dateComponents.weekday];
    
    if ([str  isEqual: @"1"]) {
        return @"周日";
    }else if ([str isEqual:@"2"]){
        return @"周一";
    }else if ([str isEqual:@"3"]){
        return @"周二";
    }else if ([str isEqual:@"4"]){
        return @"周三";
    }else if ([str isEqual:@"5"]){
        return @"周四";
    }else if ([str isEqual:@"6"]){
        return @"周五";
    }else{
        return @"周六";
    }
    
}

/** 秒数转化为时间(时,分,秒)*/
+(NSString*)df_secondConversionHourAndMinutes:(NSInteger)totalSeconds
{
    
    NSInteger seconds = totalSeconds % 60;
    NSInteger minutes = (totalSeconds / 60) % 60;
    NSInteger hours = totalSeconds / 3600;

    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",(long)hours, (long)minutes, (long)seconds];
    
}

/** 本年或者本月的第几周 第一个参数传YES 得到本年的第几周 NO为本月的第几周。*/
+(NSString *)df_getCurrentYearInWeekOrMouth:(BOOL)inYear WithDate:(NSDate *)date
{
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    //  通过已定义的日历对象，获取某个时间点的NSDateComponents表示，并设置需要表示哪些信息（NSYearCalendarUnit, NSMonthCalendarUnit, NSDayCalendarUnit等）
    
    NSDateComponents *dateComponents = [greCalendar components:NSCalendarUnitWeekOfYear | NSCalendarUnitWeekOfMonth fromDate:date];
    if (inYear) {
        return [NSString stringWithFormat:@"第%li周",(long)dateComponents.weekOfYear];
    }else{
        return [NSString stringWithFormat:@"第%li周",(long)dateComponents.weekOfMonth];
    }
    
}

/** 获取今天、明天、后天的日期*/
+(NSArray *)df_timeForTheRecentDate
{
    NSMutableArray *dateArr = [[NSMutableArray alloc]init];
    
    //今天
    NSDateFormatter *formater = [[ NSDateFormatter alloc] init];
    NSDate *curDate = [NSDate date];//获取当前日期
    [formater setDateFormat:@"YYYY-MM-dd HH:mm:ss"];//这里去掉 具体时间 保留日期
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formater setTimeZone:timeZone];
    NSString * curTime = [formater stringFromDate:curDate];
    
    NSArray *today = [self getYearAndMonthAndDayFromTimeString:curTime];
    [dateArr addObject:today];
    
    
    //明天
    NSString *timeStamp = [self timeStringIntoTimeStamp:curTime];
    NSInteger seconds = 24*60*60 + [timeStamp integerValue];
    timeStamp = [NSString stringWithFormat:@"%ld",(long)seconds];
    curTime = [self timeStampIntoTimeString:timeStamp];
    
    NSArray *tomorrow = [self getYearAndMonthAndDayFromTimeString:curTime];
    [dateArr addObject:tomorrow];
    
    
    return [NSArray arrayWithArray:dateArr];
}
+(NSArray *)getYearAndMonthAndDayFromTimeString:(NSString *)time
{
    NSString *year = [time substringToIndex:4];
    NSString *month = [[time substringFromIndex:5] substringToIndex:2];
    NSString *day = [[time substringFromIndex:8] substringToIndex:2];
    
    return @[year,month,day];
}

+ (NSString *)timeStringIntoTimeStamp:(NSString *)time
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [dateFormatter setTimeZone:timeZone];
    
    NSDate *date = [dateFormatter dateFromString:time];
    
    NSString *timeSP = [NSString stringWithFormat:@"%ld",(long)[date timeIntervalSince1970]];
    
    return timeSP;
}
+ (NSString *)timeStampIntoTimeString:(NSString *)time
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    /* 设置时区 */
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [dateFormatter setTimeZone:timeZone];
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[time intValue]];
    
    NSString *dateString = [dateFormatter stringFromDate:date];
    //dateString = [dateString substringToIndex:20];
    return  dateString;
}

+ (NSString*)df_getWeChatTimeString:(NSDate*)dt mustIncludeTime:(BOOL)includeTime
{
    NSString *ret = nil;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 当前时间
    NSDate *currentDate = [NSDate date];
    NSDateComponents *curComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday fromDate:currentDate];
    
    NSInteger currentYear = [curComponents year];
    NSInteger currentMonth = [curComponents month];
    NSInteger currentDay = [curComponents day];
    
    // 目标判断时间
    NSDateComponents *srcComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday fromDate:dt];
    NSInteger srcYear = [srcComponents year];
    NSInteger srcMonth = [srcComponents month];
    NSInteger srcDay = [srcComponents day];
    
    // 要额外显示的时间分钟
    NSString *timeExtraStr = (includeTime ? [self getTimeString:dt format:@"HH:mm"] : @"");
    // 当年
    if (currentYear == srcYear) {
        long currentTimestamp = [self getIOSTimeStamp_l:currentDate];
        long srcTimestamp = [self getIOSTimeStamp_l:dt];
        // 相差时间（单位：秒）
        long delta = currentTimestamp - srcTimestamp;
        // 当天（月份和日期一致才是）
        if(currentMonth == srcMonth && currentDay == srcDay) {
            // 时间相差60秒以内
            if (delta < 60) {
                ret = @"刚刚";
            }else {
                // 否则当天其它时间段的，直接显示“时:分”的形式
                ret = [self getTimeString:dt format:@"HH:mm"];
            }
        }else {
            // 当年 && 当天之外的时间（即昨天及以前的时间）
            // 昨天（以“现在”的时候为基准-1天）
            NSDate *yesterdayDate = [NSDate date];
            yesterdayDate = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:yesterdayDate];
            NSDateComponents *yesterdayComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday fromDate:yesterdayDate];
            NSInteger yesterdayMonth = [yesterdayComponents month];
            NSInteger yesterdayDay = [yesterdayComponents day];
            // 前天（以“现在”的时候为基准-2天）
            NSDate *beforeYesterdayDate = [NSDate date];
            beforeYesterdayDate = [NSDate dateWithTimeInterval:-48*60*60 sinceDate:beforeYesterdayDate];
            NSDateComponents *beforeYesterdayComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday fromDate:beforeYesterdayDate];
            NSInteger beforeYesterdayMonth = [beforeYesterdayComponents month];
            NSInteger beforeYesterdayDay = [beforeYesterdayComponents day];
            // 用目标日期的“月”和“天”跟上方计算出来的“昨天”进行比较，是最为准确的（如果用时间戳差值
            // 的形式，是不准确的，比如：现在时刻是2019年02月22日1:00、而srcDate是2019年02月21日23:00，
            // 这两者间只相差2小时，直接用“delta/3600” > 24小时来判断是否昨天，就完全是扯蛋的逻辑了）
            if (srcMonth == yesterdayMonth && srcDay == yesterdayDay) {
                ret = [NSString stringWithFormat:@"昨天%@", timeExtraStr]; // -1d
            }else if (srcMonth == beforeYesterdayMonth && srcDay == beforeYesterdayDay) {
                ret = [NSString stringWithFormat:@"前天%@", timeExtraStr]; // -2d
            }else {
                // 跟当前时间相差的小时数
                long deltaHour = (delta/3600);
                // 如果小于或等 7*24小时就显示星期几
                if (deltaHour <= 7*24) {
                    NSArray *weekdayAry = [NSArray arrayWithObjects:@"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
                    // 取出的星期数：1表示星期天，2表示星期一，3表示星期二。。。。 6表示星期五，7表示星期六
                    NSInteger srcWeekday = [srcComponents weekday];
                    // 取出当前是星期几
                    NSString *weedayDesc = [weekdayAry objectAtIndex:(srcWeekday-1)];
                    ret = [NSString stringWithFormat:@"%@%@",weedayDesc, timeExtraStr];
                }else {
                    ret = [NSString stringWithFormat:@"%@%@",[self getTimeString:dt format:@"yyyy/M/d"], timeExtraStr];
                }
            }
        }
    }else {
        // 往年
        ret = [NSString stringWithFormat:@"%@%@", [self getTimeString:dt format:@"yyyy/M/d"], timeExtraStr];
    }
    return ret;
}
+ (NSString*)getTimeString:(NSDate*)dt format:(NSString*)fmt {
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:fmt];
    return [format stringFromDate:(dt == nil ? [self getIOSDefaultDate] : dt)];
}
+ (NSTimeInterval) getIOSTimeStamp:(NSDate*)dat {
    NSTimeInterval a = [dat timeIntervalSince1970];
    return a;
}

+ (long) getIOSTimeStamp_l:(NSDate*)dat {
    return [[NSNumber numberWithDouble:[self getIOSTimeStamp:dat]] longValue];
}

+ (NSDate*)getIOSDefaultDate {
    return [NSDate date];
}

@end
